package com.example.com.transcribeeditpublish.activity;

import android.Manifest;

import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.HandlerThread;

import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewCompat;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.example.com.transcribeeditpublish.BR;
import com.example.com.transcribeeditpublish.R;
import com.example.com.transcribeeditpublish.databinding.ActivityLocalVideoImgBinding;
import com.example.com.transcribeeditpublish.fragement.PictureChooseFragment;
import com.example.com.transcribeeditpublish.fragement.VideoChooseFragment;
import com.example.com.transcribeeditpublish.utils.TCConstants;
import com.example.com.transcribeeditpublish.utils.TCVideoEditUtil;
import com.example.com.transcribeeditpublish.utils.TCVideoFileInfo;
import com.example.com.transcribeeditpublish.utils.VideoPreareUtils;

import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.widget.CustomProgressDialog;

import com.tbruyelle.rxpermissions2.RxPermissions;
import com.tencent.liteav.basic.log.TXCLog;
import com.tencent.ugc.TXVideoEditConstants;

import java.io.File;
import java.util.ArrayList;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import me.goldze.mvvmhabit.base.BaseActivity;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.utils.ToastUtils;

/**
 * Created by i7-1 on 2018/12/11.
 */

public class LocalVideoImgActivity extends BaseActivity<ActivityLocalVideoImgBinding, BaseViewModel> {
    private String[] tabIndicators = {"视频", "图片"};
    private HandlerThread mHandlerThread;
    private Handler mHandler;
    private VideoChooseFragment mVideoChooseFragment;
    private PictureChooseFragment mPictureChooseFragment;
    private String TAG = "LocalVideoImgActivity";


    @Override
    public int initContentView() {
        return R.layout.activity_local_video_img;
    }

    @Override
    public int initVariableId() {
        return BR.entity;
    }

    @Override
    public BaseViewModel initViewModel() {
        return new BaseViewModel(this);
    }

    @Override
    public void initData() {
        super.initData();
        initView();
        initHandler();
        requestPermission();
    }

    private void initView() {
        TextView r = getBinding().getRoot().findViewById(R.id.r_text);
        r.setText("下一步>");
        r.setVisibility(View.VISIBLE);
        r.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                toEdit();
            }
        });

        getBinding().localTable.setTabMode(TabLayout.MODE_FIXED);
        getBinding().localTable.setTabTextColors(getResources().getColor(R.color.gray), getResources().getColor(R.color.white));
        getBinding().localTable.setSelectedTabIndicatorHeight(2);
        getBinding().localTable.setSelectedTabIndicatorColor(Color.WHITE);
        ViewCompat.setElevation(getBinding().localTable, 10);

        getBinding().localTable.setupWithViewPager(getBinding().lVp);
        for (int i = 0; i < 2; i++) {
            TabLayout.Tab itemTab = getBinding().localTable.getTabAt(i);
            if (itemTab != null) {
                itemTab.setCustomView(R.layout.item_tab_layout_local);
                TextView itemTv = itemTab.getCustomView().findViewById(R.id.l_title);
                itemTv.setText(i == 0 ? "视频" : "图片");
            }
        }

        ArrayList<Fragment> mList = new ArrayList<Fragment>();
        mVideoChooseFragment = new VideoChooseFragment();
        mPictureChooseFragment = new PictureChooseFragment();
        mList.add(mVideoChooseFragment);
        mList.add(mPictureChooseFragment);

        TabFragmentPagerAdapter mAdapter = new TabFragmentPagerAdapter(getSupportFragmentManager(), mList);
        getBinding().lVp.setAdapter(mAdapter);

    }


    private void initHandler() {
        getBinding().lVp.setCurrentItem(0);
        mHandlerThread = new HandlerThread("LoadList");
        mHandlerThread.start();
        mHandler = new Handler(mHandlerThread.getLooper());
    }

    private void requestPermission() {
        RxPermissions rxPermissions = new RxPermissions(LocalVideoImgActivity.this);
        rxPermissions.request(Manifest.permission.READ_EXTERNAL_STORAGE)
                .subscribe(new Observer<Boolean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(Boolean value) {
                        if (value) {
                            mHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    initViewImg();
                                }
                            });
                        } else {
                            Toast.makeText(LocalVideoImgActivity.this, "拒绝权限", Toast.LENGTH_SHORT).show();
                            LocalVideoImgActivity.this.finish();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }

    private void initViewImg() {
        mVideoChooseFragment.loadVideoList();
        mPictureChooseFragment.loadPictureList();
    }


    private class TabFragmentPagerAdapter extends FragmentPagerAdapter {
        private final ArrayList<Fragment> mList;

        public TabFragmentPagerAdapter(android.support.v4.app.FragmentManager supportFragmentManager, ArrayList<Fragment> mList) {
            super(supportFragmentManager);
            this.mList = mList;
        }

        @Override
        public int getCount() {
            return mList.size();
        }

        @Override
        public Fragment getItem(int position) {
            return mList.get(position);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return tabIndicators[position];
        }
    }

    private void toEdit() {
        if (getBinding().lVp.getCurrentItem() == 0) {
            TCVideoFileInfo singleSelected = mVideoChooseFragment.getmAdapter().getSingleSelected();
            if (singleSelected != null) {
                doSelectVideo(singleSelected);
            } else {
                ToastUtils.showShort("未选择视频");

            }
        } else {
            ArrayList<TCVideoFileInfo> inOrderMultiSelected = mPictureChooseFragment.getmAdapter().getInOrderMultiSelected();
            if (inOrderMultiSelected != null && inOrderMultiSelected.size() > 0) {
                doSelectImg(inOrderMultiSelected);
            } else {
                ToastUtils.showShort("未选择图片");

            }
        }

    }

    private void doSelectVideo(final TCVideoFileInfo fileInfo) {
        KLog.e(fileInfo.getFilePath());
        if (fileInfo == null) {
            TXCLog.d(TAG, "select file null");
            ToastUtils.showShort("未选择视频");
            return;
        }
        if (TCVideoEditUtil.isVideoDamaged(fileInfo)) {
            ToastUtils.showShort("该视频文件已经损坏");
            return;
        }
        if (fileInfo.getDuration() < 15 * 1000) {
            ToastUtils.showShort("视频时长最低15s");
            return;
        }
        File file = new File(fileInfo.getFilePath());
        if (!file.exists()) {
            ToastUtils.showShort("选择的文件不存在");
            return;
        }
        showDialog();
        VideoPreareUtils.preareEdit(this, fileInfo.getFilePath(), new VideoPreareUtils.PreareCallback() {
            @Override
            public void callback(TXVideoEditConstants.TXVideoInfo info) {
                if (info != null) {
                    startEditVideo(fileInfo);
                }
            }
        });


    }

    private void startEditVideo(TCVideoFileInfo fileInfo) {
        Intent intent = new Intent(this, VideoSimpleActivity.class);
        intent.putExtra(TCConstants.VIDEO_EDITER_IMPORT, false);
        intent.putExtra(TCConstants.VIDEO_EDITER_PATH, fileInfo.getFilePath());
        intent.putExtra(TCConstants.VIDEO_RECORD_COVERPATH, fileInfo.getThumbPath());
        startActivity(intent);
        //finish();
    }

    private void doSelectImg(ArrayList<TCVideoFileInfo> pictureList) {
        Intent intent = new Intent(this, PictureEditerActivity.class);

        if (pictureList == null || pictureList.size() == 0) {
            TXCLog.d(TAG, "select file null");
            return;
        }
        ArrayList picturePathList = new ArrayList();
        for (TCVideoFileInfo info : pictureList) {
            File file = new File(info.getFilePath());
            if (!file.exists()) {
                TCVideoEditUtil.showErrorDialog(this, "选择的文件不存在");
                return;
            }
            picturePathList.add(info.getFilePath());
        }
        intent.putStringArrayListExtra(TCConstants.INTENT_KEY_MULTI_PIC_LIST, picturePathList);
        startActivity(intent);
        finish();
    }

    @Override
    protected void onStop() {
        super.onStop();
        dismissDialog();
    }
}
